package mvc.controller;

import mvc.config.MyBatisConfig;
import mvc.entity.User;
import mvc.mapper.UserMapper;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


@Controller
public class CheckNameController {
    @RequestMapping(value = "/name.do", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String checkname(String username) {
        System.out.println("checkname开始");
        System.out.println(username);

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyBatisConfig.class);
        /*UserMapper um = ctx.getBean("userMapper",UserMapper.class);
        Integer sum = um.getUserByName(username);
        if ("1".equals(sum)){
            System.out.println("用户名已存在");
            return "用户名已存在";
        }else {
            System.out.println("用户名可用");
            return "用户名可用";
        }*/
        DataSource dataSource = ctx.getBean("dataSource",DataSource.class);
        try (Connection conn = dataSource.getConnection()) {
            String sql = "select username from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                System.out.println("用户名已存在");
                return "用户名已存在";
            }else {
                System.out.println("用户名可用");
                return "用户名可用";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping(value = "/LoginName.do", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String checkLoginName(String username) {
        System.out.println("checkLoginName开始");
        System.out.println(username);
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyBatisConfig.class);
        DataSource dataSource = ctx.getBean("dataSource",DataSource.class);
        try (Connection conn = dataSource.getConnection()) {
            String sql = "select username from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                System.out.println("用户名存在");
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("用户名不存在");
        return "用户名不存在";
    }
}
